//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System;
using System.Collections;
using System.Web.UI;
using System.Web.UI.WebControls;
using CommunityServer.Blogs.Components;
using CommunityServer.Components;
using CommunityServer.ControlPanel.UI;
using CommunityServer.Controls;

using ResourceControl = CommunityServer.ControlPanel.Controls.ResourceControl;
using ResourceLinkButton = CommunityServer.ControlPanel.Controls.ResourceLinkButton;
using ResourceManager = CommunityServer.ControlPanel.Components.ResourceManager;

namespace CommunityServer.ControlPanel.Blogs
{


	/// <summary>
	///		Summary description for PostListControl.
	/// </summary>
	public class PostListControl : UserControl
	{

		#region Controls

        protected DropDownList MonthList;
        protected DropDownList CategoryList;
        protected ResourceLinkButton Button1;
		protected ResourceLinkButton NewPost;
        protected Modal Modal1;
		protected ResourceControl FeedbackFilterLabel;
		protected DropDownList filterPublished;
		protected string DeleteWarning;
        protected Repeater theposts;
        protected IPagedControl thePager;

		#endregion

        protected BaseBlogPage BlogPage
        {
            get {return this.Page as BaseBlogPage;}
        }

        protected Weblog CurrentWeblog
        {
            get { return this.BlogPage.CurrentWeblog;}
        }

        private BlogPostType bpt = BlogPostType.Post;
        public virtual BlogPostType BlogPostType
        {
            get{return bpt;}
            set {bpt = value;}
        }

		override protected void OnInit(EventArgs e)
		{
			this.Load += new EventHandler(this.Page_Load);
			base.OnInit(e);
			this.Button1.Click += new EventHandler(this.Button1_Click);
			this.NewPost.Click += new EventHandler(this.NewPost_Click);
		}
		
		private void Page_Load(object sender, EventArgs e)
        {
            theposts.ItemCommand +=new RepeaterCommandEventHandler(theposts_ItemCommand);
            theposts.ItemCreated +=new RepeaterItemEventHandler(theposts_ItemCreated);

			if (this.BlogPostType == BlogPostType.Article)
				DeleteWarning	= Components.ResourceManager.GetString("CP_Blog_PostList_DeleteArticle_Warning");
			else
				DeleteWarning	= Components.ResourceManager.GetString("CP_Blog_PostList_DeletePost_Warning");

			if(!Page.IsPostBack && !BlogPage.IsCallBack)
            {
                BindFilters();
                ConfigurePage();
                buildGrid();
            }
        }


	    private void BindFilters()
	    {
	    	ArrayList al = PostCategories.GetCategories(CurrentWeblog.SectionID,true);
	        foreach(PostCategory pc in al)
	        {
	            CategoryList.Items.Add(new ListItem(Server.HtmlDecode(pc.Name) ,pc.CategoryID.ToString()));
	        }
	        CategoryList.Items.Insert(0,new ListItem(Components.ResourceManager.GetString("CP_Blog_Category") ,"-1"));
    
            if(this.BlogPostType == BlogPostType.Post)
            {
                al = WeblogPosts.GetPostsByMonths(CurrentWeblog.SectionID);
    
                foreach(ArchiveDataItem adi in al)
                {
                    int month = adi.Date.Year * 12 + adi.Date.Month;
                    MonthList.Items.Add(new ListItem(adi.Date.ToString("MMMM yyyy"),month.ToString()));
                }
            }
            else
            {
                MonthList.Visible = false;
            }
	        MonthList.Items.Insert(0,new ListItem(Components.ResourceManager.GetString("CP_Blog_Month"),"-1"));

			filterPublished.Items.Add(new ListItem(Components.ResourceManager.GetString("Feedback_SelectAll"), ((int)BlogPostPublishedFilter.All).ToString()));
			filterPublished.Items.Add(new ListItem(Components.ResourceManager.GetString("Feedback_FilterPublished"), ((int)BlogPostPublishedFilter.Published).ToString()));
			filterPublished.Items.Add(new ListItem(ResourceManager.GetString("Feedback_FilterNotPublished"), ((int)BlogPostPublishedFilter.NotPublished).ToString()));
		}

        private void ConfigurePage()
        {
            CSContext context = CSContext.Current;

            //int ps = context.GetIntFromQueryString("ps",10);
            int categoryid = context.GetIntFromQueryString("cid",-1);
            int m = context.GetIntFromQueryString("m",-1);
			int ip = context.GetIntFromQueryString("ip", (int)BlogPostPublishedFilter.All);

            ListItem li = MonthList.Items.FindByValue(m.ToString());
            if(li != null)
                li.Selected = true;

            li = CategoryList.Items.FindByValue(categoryid.ToString());
            if(li != null)
                li.Selected = true;

			if (this.BlogPostType == BlogPostType.Article)
				NewPost.ResourceName = "CP_Blog_CreateArticle";

			li = filterPublished.Items.FindByValue(ip.ToString());
			if(li != null)
				li.Selected = true;
            
//            if(MonthList.SelectedIndex > 0 || CategoryList.SelectedIndex > 0 || filterPublished.SelectedValue == ((int)BlogPostPublishedFilter.NotPublished).ToString()) 
//                this.GridMode = CA.GridRunningMode.Client;
//            else
//				this.GridMode = CA.GridRunningMode.Callback;    
         
        }

        protected void buildGrid()
        {
            CSContext context = CSContext.Current;

            int categoryid = context.GetIntFromQueryString("cid",-1);
            int ym = context.GetIntFromQueryString("m",-1);
			int ip = context.GetIntFromQueryString("ip", (int)BlogPostPublishedFilter.All);


			BlogThreadQuery query = new BlogThreadQuery();
            query.SectionID = CurrentWeblog.SectionID;
            query.BlogPostType = this.BlogPostType;

			// Show posts for an inactive section if the user is an admin
			query.RequireSectionIsActive = !(context.User.IsBlogAdministrator || context.User.IsAdministrator);


				query.PageIndex = context.PageIndex;
				query.PageSize = Globals.SafeInt(context.User.GetExtendedAttribute("CPPageSize"),10);


			if(categoryid > -1)
                query.CategoryID = categoryid;

            if(ym > -1)
            {
               int y = ym/12;
                int m = ym%12;

                if(m == 0)
                {
                    m = 12;
                    y = y -1;
                }

                DateTime dt = new DateTime(y,m,1);

                query.DateFilter = dt;
                query.BlogThreadType = BlogThreadType.Month;
            }

			query.PublishedFilter = (BlogPostPublishedFilter)ip;

            query.SortOrder = SortOrder.Descending;

			
            ThreadSet ts = WeblogPosts.GetBlogThreads(query,false);


            theposts.DataSource = ts.Threads;
            theposts.DataBind();

            thePager.PageIndex = query.PageIndex;
            thePager.PageSize = query.PageSize;
            thePager.TotalRecords = ts.TotalRecords;
          
        }

		#region Button Clicks

        private void Button1_Click(object sender, EventArgs e)
        {
            Redirect(false);
        }

        void Redirect(bool includePage)
        {
            string url  = "{0}?cid={1}&m={2}&ip={3}";
            url = string.Format(url,Request.Path,Globals.SafeInt(CategoryList.SelectedValue,-1) , Globals.SafeInt(MonthList.SelectedValue,-1) , Globals.SafeInt(filterPublished.SelectedValue, -1) );
            if(includePage)
                Response.Redirect(url + "&PageIndex=" + (CSContext.Current.PageIndex + 1).ToString());
            else
                Response.Redirect(url);
        }

		private void NewPost_Click(object sender, EventArgs e)
		{
			Response.Redirect(BlogUrls.Instance().PostEditor(this.CurrentWeblog.SectionID, this.BlogPostType));
		}

        #endregion

        private void theposts_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if(e.CommandName == "Delete")
            {
                int postid = Globals.SafeInt(e.CommandArgument.ToString(), -1);
                if(postid > -1)
                {
                    WeblogPost wp = WeblogPosts.GetPost(postid,false,false,true);
                    if(wp != null && wp.SectionID == this.CurrentWeblog.SectionID)
                    {
                        WeblogPosts.Delete(wp,CSContext.Current.User.UserID);
                    }
                    else
                    {
                        throw new CSException(CSExceptionType.AccessDenied,"The deleted post is not in the current section or the post does not exist");
                    }
                }

            }

            Redirect(true);
        }

        private void theposts_ItemCreated(object sender, RepeaterItemEventArgs e)
        {
            if(e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                LinkButton lb = e.Item.FindControl("DeleteButton") as LinkButton;
                if(lb != null)
                {
                     if (this.BlogPostType == BlogPostType.Article)
                        lb.Attributes.Add("onclick","return confirm('" + Components.ResourceManager.GetString("CP_Blog_PostList_DeleteArticle_Warning") + "');");
                    else
                        lb.Attributes.Add("onclick","return confirm('" + Components.ResourceManager.GetString("CP_Blog_PostList_DeletePost_Warning") + "');");
                }
            }
        }
    }
}
